Command Method
It encapsulates a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. This pattern decouples the sender of a request from its receiver, allowing for better flexibility and control over the execution of requests.
Structure
- Command Interface: Declares a method for executing a command.
- Concrete Command: Implements the command interface and defines the binding between a receiver and an action.
- Receiver: Knows how to perform the operations associated with the command.
- Invoker: Asks the command to execute the request.
- Client: Creates the command and associates it with a receiver.
Example
// Command Interface
interface Command {
void execute();
}
// Concrete Command for turning on the light
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
// Concrete Command for turning off the light
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
// Receiver class
class Light {
public void turnOn() {
System.out.println("Light is ON");
}
public void turnOff() {
System.out.println("Light is OFF");
}
}
// Invoker class
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Client code
public class Main {
public static void main(String[] args) {
Light livingRoomLight = new Light();
// Create Command Objects
Command lightOn = new LightOnCommand(livingRoomLight);
Command lightOff = new LightOffCommand(livingRoomLight);
// Create Invoker
RemoteControl remote = new RemoteControl();
// Turn the light ON
remote.setCommand(lightOn);
remote.pressButton(); // Output: Light is ON
// Turn the light OFF
remote.setCommand(lightOff);
remote.pressButton(); // Output: Light is OFF
}
}